import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:erp/data/model/login_response.dart';
import 'package:erp/routes/app_pages.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'data/api/dictionary_api.dart';
import 'data/api/hr_api.dart';
import 'data/model/dict.dart';
import 'data/model/option.dart';

class MainState extends GetxController {
  Rx<Token?> token = Rx<Token?>(null);
  Rx<UserInfo?> userInfo = Rx<UserInfo?>(null);

  final List<String> menuCodeList = [];

  // 字典
  final Map<String, List<Option>> _dictMap = {};
  final Map<String, Map<String, String>> _dictTranslationMap = {};

  // 人员
  final Map<int, String> empIdTranslation = {};

  // 组织
  final Map<int, String> orgIdTranslation = {};

  /// 可以存常用字典
  @override
  void onInit() {
    super.onInit();
  }

  Future<void> loadSomething() async {
    var empData = await HrApi.selectAllEmp();
    empIdTranslation.addEntries((empData as List).map((element) => MapEntry(element['id'], element['empName'])));
    var orgData = await HrApi.selectAllOrg();
    orgIdTranslation.addEntries((orgData as List).map((element) => MapEntry(element['id'], element['orgName'])));
  }

  /// 加载字典表
  Future<void> loadDictionary() async {
    List<String> queryList = [
      'area_dept',
      'company',
      'build_type',
      'project_category',
      'charge_dept',
      'project_source',
      'bid_mode',
      'bid_status',
      'build_type',
    ];
    // 批量调用字典查询接口
    Map<String, dynamic> map = await DictionaryApi.queryDictCodeList(queryList);
    Iterable<MapEntry<String, List<Option>>> iterable = map.entries.map((entry) {
      var key = entry.key;
      var list = entry.value as List;

      Map<String, String> translateMap = {};

      var _entry = MapEntry(
        key,
        list.map<Dict>((m) => Dict.fromJson(m)).map((e) {
          translateMap[e.dictValue] = e.dictLabel;
          return Option.from(e.dictLabel, e.dictValue);
        }).toList(),
      );
      _dictTranslationMap[key] = translateMap;
      return _entry;
    });
    _dictMap.addEntries(iterable);
  }

  List<Option> getOptions(String key) {
    return _dictMap[key] ?? [];
  }

  Map<String, String> getTranslation(String key) {
    return _dictTranslationMap[key] ?? {};
  }

  void setAuth(dynamic data) {
    SharedPreferences sp = Get.find<SharedPreferences>();
    LoginResponse loginResponse = LoginResponse.fromJson(data);
    List menuList = data["userAuthInfo"]["menuList"] as List;
    this.menuCodeList.addAll(menuList.map((e) => e["menuCode"]));
    sp.setString("token", loginResponse.token.toString());
    sp.setString("userInfo", loginResponse.userInfo.toString());
    sp.setString("menuCodeList", JsonUtil.encodeObj(this.menuCodeList) ?? "");
    this.token.value = loginResponse.token;
    this.userInfo.value = loginResponse.userInfo;
  }

  void clearAuth() {
    SharedPreferences sp = Get.find<SharedPreferences>();
    sp.remove("token");
    sp.remove("userInfo");
    sp.remove("menuCodeList");
    this.token.value = null;
    this.userInfo.value = null;
    this.menuCodeList.clear();
    Get.offAllNamed(Routes.LOGIN);
  }
}
